package com.tinyengine.it.config;

import com.tinyengine.it.common.utils.GenDir;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

@Slf4j
@Configuration
public class ZipExtractor implements ApplicationRunner {

    private static final String ZIP_FILE_NAME = "templates.zip"; // 资源文件名
    private static final String SOURCE_TEMPLATE_DIR = GenDir.getSpringOptSourcePathBasedOnOS();  // 目标解压目录

    @Override
    public void run(ApplicationArguments args) throws Exception {
        //if (SOURCE_TEMPLATE_DIR.contains("D")) {
        //    return;
        //}
        try {
            String pathStr = SOURCE_TEMPLATE_DIR;
            if ("未知操作系统路径".equals(pathStr)) {
                throw new IllegalStateException("不支持的操作系统，无法创建存放模板文件目录");
            }

            Path path = Paths.get(pathStr);
            if (Files.notExists(path)) {
                Files.createDirectories(path);
                log.info("存放模板文件目录已创建：{}", path);
            } else {
                log.info("存放模板文件目录已存在：{}", path);
            }
        } catch (Exception e) {
            log.error("创建存放模板文件目录失败", e);
            throw new RuntimeException("初始化 存放模板文件目录 时出错", e);
        }

        // 读取 classpath 目录下的 templates.zip
        ClassPathResource zipResource = new ClassPathResource(ZIP_FILE_NAME);
        if (!zipResource.exists()) {
            log.info("文件不存在：" + ZIP_FILE_NAME);
            return;
        }

        // 复制 ZIP 文件到临时目录（Windows 兼容）
        String tempDir = System.getProperty("java.io.tmpdir"); // 获取系统临时目录
        File targetZip = new File(tempDir, "templates.zip"); // 拼接临时文件路径

        // 删除临时文件（如果已存在）
        if (targetZip.exists()) {
            if (targetZip.delete()) {
                log.info("已删除旧的临时文件：" + targetZip.getAbsolutePath());
            } else {
                log.info("无法删除临时文件：" + targetZip.getAbsolutePath());
            }
        }

        log.info("复制 ZIP 文件到：" + targetZip.getAbsolutePath());

        try (InputStream zipStream = zipResource.getInputStream()) {
            Files.copy(zipStream, targetZip.toPath(), StandardCopyOption.REPLACE_EXISTING);
        }

        // 解压 ZIP 文件
        unzip(new FileInputStream(targetZip), SOURCE_TEMPLATE_DIR);
        log.info("bladex.zip 解压成功，路径：" + SOURCE_TEMPLATE_DIR);
    }

    /**
     * 解压 ZIP 文件到目标目录
     */
    private void unzip(InputStream zipInputStream, String targetDir) throws IOException {
        try (ZipInputStream zis = new ZipInputStream(zipInputStream)) {
            ZipEntry zipEntry;
            while ((zipEntry = zis.getNextEntry()) != null) {
                File newFile = new File(targetDir, zipEntry.getName());
                if (zipEntry.isDirectory()) {
                    newFile.mkdirs();
                } else {
                    // 确保父目录存在
                    new File(newFile.getParent()).mkdirs();
                    try (FileOutputStream fos = new FileOutputStream(newFile)) {
                        byte[] buffer = new byte[1024];
                        int len;
                        while ((len = zis.read(buffer)) > 0) {
                            fos.write(buffer, 0, len);
                        }
                    }
                }
                zis.closeEntry();
            }
        }
    }
}
